﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Sunny.Entity;
using Sunny.Model.RequestParam;

namespace Sunny.Service
{
    public class LoginLogService
    {
        private readonly SunnyContext _sunnyContext;

        public LoginLogService(SunnyContext sunnyContext)
        {
            _sunnyContext = sunnyContext;
        }
        
        public async Task Add(SysLoginLog sysLoginLog)
        {
            await _sunnyContext.SysLoginLog.AddAsync(sysLoginLog);
            await _sunnyContext.SaveChangesAsync();
        }

        public async Task<(List<SysLoginLog>, int)> List(LoginLogListParam param)
        {
            var logs = _sunnyContext.SysLoginLog.AsQueryable();
            if(!string.IsNullOrEmpty(param.IpAddr))
            {
                logs = logs.Where(t=>t.Ipaddr.Contains(param.IpAddr));
            }
            if(!string.IsNullOrEmpty(param.UserName))
            {
                logs= logs.Where(t=>t.UserName.Contains(param.UserName));
            }
            if(!string.IsNullOrEmpty(param.Status))
            {
                logs = logs.Where(t=>t.Status == param.Status);
            }
            if(param.CreateTime!=null && param.CreateTime.Length == 2)
            {
                logs = logs.Where(t=>t.LoginTime>=param.CreateTime[0] && t.LoginTime<= param.CreateTime[1]);
            }
            int total = await logs.CountAsync();
            var logList = await logs.OrderByDescending(t=>t.LoginTime).Skip((param.PageNum-1)*param.PageSize).Take(param.PageSize).ToListAsync();
            return (logList,total);
        }

        public async Task BatchDelete(string logIds)
        {
            var strLogIds = logIds.Split(",");
            var lIds = Array.ConvertAll(strLogIds,long.Parse);
            var loginLogs = _sunnyContext.SysLoginLog.Where(t=>lIds.Contains(t.LogId));
            _sunnyContext.SysLoginLog.RemoveRange(loginLogs);
            await _sunnyContext.SaveChangesAsync();
        }

        public async Task DeleteAll()
        {
            var loginLogs = _sunnyContext.SysLoginLog.AsQueryable();
            _sunnyContext.SysLoginLog.RemoveRange(loginLogs);
            await _sunnyContext.SaveChangesAsync();
        }
    }
}